package com.ftd.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ftd.model.Ebook;
import org.apache.http.client.fluent.Content;
import org.apache.http.client.fluent.Request;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.ArrayList;

/**
 * Created by apple on 16/7/30.
 */
@Controller
@RequestMapping(value = "/hibook")
public class EbookViewController {
    @RequestMapping(value = "getEbookJson")
    @ResponseBody
    public ArrayList getEbookJson() throws IOException {
        //准备工作
        //将keyword转变为UTF-8的一种编码
        //函数式的发送请求并返回content对象
        Content content = Request.Get("http://apis.juhe.cn/goodbook/query?catalog_id=252&pn=1&rn=30&dtype=&key=f5094a267c16bde9818bb0da9fc26443")
                .execute().returnContent();

        //content是json的一个对象,将其转换成String
        String jsonString = content.asString();
        //讲json字符串转变成json对象
        JSONObject jsonObject = JSON.parseObject(jsonString);
        //获取json的result对象
        JSONObject resultObject = jsonObject.getJSONObject("result");
        //获取result对象里的data的json数组
        JSONArray jsonArray = resultObject.getJSONArray("data");


//        System.out.print(jsonArray);
        //声明一个module的数组
        ArrayList moduleArray = new ArrayList();
        //讲json中的部分数据导入数组
        for (int i = 0; i < jsonArray.size(); i++) {
            moduleArray.add(new Ebook(jsonArray.getJSONObject(i)));
//            System.out.println(jsonArray.getJSONObject(i));
        }
//        Ebook book =  new Ebook(jsonArray.getJSONObject(1));
//        System.out.println(book.geteBookName());

        // 可以把对象以字符串形式返回. JSON.toJSONString()

        return moduleArray;
    }

    @RequestMapping(value = "ebookView")
    public String ebookView(){

        return "ebookView";
    }
}
